package com.siwei.mes.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.siwei.mes.common.annotation.AnonymousAccess;
import com.siwei.mes.entity.system.User;
import com.siwei.mes.service.system.UserService;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenmaolin
 * @date 2021-11-19
 */
@Component
public class SaTokenLoginInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;

    private static UserService serial;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        serial = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 匿名访问注解
            AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
            if (null != anonymousAccess) {
                return true;
            }
        }
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

        StpUtil.checkLogin();
        /**这里判断用户是否删除*/
        boolean login = StpUtil.isLogin();
        if (login) {
            if (StpUtil.getLoginIdAsLong() == 99999999) {
                return true;
            }

            User user = serial.loadById(StpUtil.getLoginIdAsLong());
            if (user == null) {
                throw NotLoginException.newInstance("1", "-2", "token 无效", StpUtil.getTokenValue()).setCode(11012);
            } else {
                Object extra = StpUtil.getExtra("password");
                if (extra != null) {
                    String lastPassword = String.valueOf(extra);
                    String nowPassword = user.getPassword();
                    if (!lastPassword.equals(nowPassword)) {
                        throw NotLoginException.newInstance("1", "-3", "token 已过期", StpUtil.getTokenValue()).setCode(11012);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除对象
    }
}
